 package com.lion.appletrip;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.VolleyError;
import com.lion.appletrip.model.GridViewShareActivity.Comment;
import com.lion.appletrip.model.GridViewShareActivity.DetailList;
import com.lion.appletrip.model.GridViewShareActivity.User;
import com.lion.appletrip.utils.ConstantsCustomer;
import com.lion.appletrip.utils.CustomerGridView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xinbo.utils.HTTPUtils;
import com.xinbo.utils.UILUtils;
import com.xinbo.utils.VolleyListener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class GridViewShareActivity extends Activity
{

	private ListView mListView;
	private View btnBack;
	private View btnCollect;
	private View btnShare;
	private List<DetailList> detailLists = new ArrayList<DetailList>();
	private List<Comment> commentsList = new ArrayList<Comment>();
	private MyAdapter adapter;
	private ImageView ivAvatarS;
	private TextView tvNameUser;
	private TextView tvTitle;
	private TextView tvNameTrip;
	private TextView tvDataTour;
	private TextView tvRecommendationsCount;
	private LinearLayout mLayout;
	private TextView tvCommentsSize;
	private ListAdapter listAdapter;
	private ImageView ivAvatarMRecommendations;
	private View lionGrid;
	private String url;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_grid_view_share);
		Intent intent = getIntent();
		long spotId = intent.getLongExtra("spotId", 0);
		Log.e("spotId", spotId + "");
		url = ConstantsCustomer.url.SHARE_URL + "?spot_id=" + spotId + "&spot_id="
		        + spotId;
		initUI();
		initListener();
		adapter = new MyAdapter();
		mListView.setAdapter(adapter);
	}

	private void initListener()
	{
		btnBack.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				finish();
			}
		});

	}

	private void initUI()
	{
		mListView = (ListView) findViewById(R.id.listView1_gridviewshareactivity);
		lionGrid = findViewById(R.id.lion_grid);
		View headview = getLayoutInflater().inflate(
		        R.layout.gridviewshareactivity_listview_headview, null);
		View footview = getLayoutInflater().inflate(
		        R.layout.gridviewshareactivity_listview_footview, null);
		btnBack = findViewById(R.id.btn_back_gridviewactivity);
		btnCollect = findViewById(R.id.btn_collect_gridview);
		btnShare = findViewById(R.id.btn_share_gridview);
		ivAvatarS = (ImageView) headview.findViewById(R.id.iv_avatar_s2);
		tvNameUser = (TextView) headview.findViewById(R.id.tv_name_user);
		tvTitle = (TextView) headview.findViewById(R.id.tv_title_spot);
		tvNameTrip = (TextView) footview.findViewById(R.id.tv_name_trip);
		tvDataTour = (TextView) footview.findViewById(R.id.tv_date_tour);
		tvRecommendationsCount = (TextView) footview
		        .findViewById(R.id.tv_recommendations_count);
		ivAvatarMRecommendations = (ImageView) footview
		        .findViewById(R.id.iv_avatar_m_recommendations);
		mLayout = (LinearLayout) footview.findViewById(R.id.mlinear012);
		tvCommentsSize = (TextView) footview
		        .findViewById(R.id.tv_comments_size);
		CustomerGridView mGridView = (CustomerGridView) footview
		        .findViewById(R.id.customerGridView1);
		listAdapter = new ListAdapter();
		mGridView.setAdapter(listAdapter);
		mListView.addHeaderView(headview, null, false);
		mListView.addFooterView(footview, null, false);
		initData();
	}

	private void initData()
	{
		HTTPUtils.get(this, url, new VolleyListener()
		{

			@Override
			public void onResponse(String json)
			{
				jsonToText(json);

			}

			@Override
			public void onErrorResponse(VolleyError arg0)
			{

			}
		});
	}

	protected void jsonToText(String json)
	{
		commentsList.clear();
		detailLists.clear();
		try
		{
			JSONObject jsonObject = new JSONObject(json);
			Log.e("json===", json);
			JSONObject data = jsonObject.getJSONObject("data");
			JSONObject spot = data.getJSONObject("spot");

			String text = spot.getString("text");
			tvTitle.setText(text);

			String datatour = spot.getString("date_tour");
			tvDataTour.setText(datatour);

			int recommendationsCount = spot.getInt("recommendations_count");
			tvRecommendationsCount.setText(recommendationsCount + "人喜欢");
			JSONArray recommendations = spot.getJSONArray("recommendations");
			initRecommendations(recommendations);
			JSONArray comments = spot.getJSONArray("comments");

			for (int i = 0; i < comments.length(); i++)
			{
				JSONObject comment = comments.getJSONObject(i);
				String commentdata = comment.getString("comment");
				long dateAdded = comment.getLong("date_added");
				JSONObject userData = comment.getJSONObject("user");
				String name = userData.getString("name");
				String avatarS = userData.getString("avatar_m");
				User user = new User(name, avatarS);
				Comment comment2 = new Comment(commentdata, dateAdded, user);
				commentsList.add(comment2); 
				user = null;
				comment2 = null;
			}

			tvCommentsSize.setText(comments.length() + "人评论");

			JSONArray detail = spot.getJSONArray("detail_list");
			for (int i = 0; i < detail.length(); i++)
			{
				JSONObject detailData = detail.getJSONObject(i);
				String photoS = detailData.getString("photo_s");
				String text_ = detailData.getString("text");
				DetailList detailList = new DetailList(photoS, text_);
				detailLists.add(detailList);
				detailList = null;
			}

			JSONObject trip = data.getJSONObject("trip");
			String name_trip = trip.getString("name");
			tvNameTrip.setText(name_trip);

			JSONObject userData = trip.getJSONObject("user");
			String name = userData.getString("name");
			String avatarS = userData.getString("avatar_m");
			User user = new User(name, avatarS);
			tvNameUser.setText(user.getName());
			UILUtils.displayImageNoAnim(user.getAvatarS(), ivAvatarS);
		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		lionGrid.setVisibility(View.VISIBLE);

		listAdapter.notifyDataSetChanged();
		adapter.notifyDataSetChanged();

	}

	private void initRecommendations(JSONArray recommendations)
	{
		JSONObject recommendation;
		try
		{
			if (recommendations.length() > 0)
			{
				recommendation = recommendations.getJSONObject(0);
				String avatarM = recommendation.getString("avatar_m");
				UILUtils.displayImageNoAnim(avatarM, ivAvatarMRecommendations);
				if (recommendations.length() > 1)
				{
					for (int i = 1; i < recommendations.length(); i++)
					{
						JSONObject recommendation2 = recommendations
						        .getJSONObject(i);
						String avatarM2 = recommendation2.getString("avatar_m");
						View layout = getLayoutInflater()
						        .inflate(
						                R.layout.gridviewshareactivity_listview_footview_item,
						                null);
						ImageView mImageView = (ImageView) layout
						        .findViewById(R.id.iv_avatar_m_recommendations2);
						UILUtils.displayImageNoAnim(avatarM2, mImageView);
						LayoutParams layoutParams = layout.getLayoutParams();
						if (i < 7)
						{
							mLayout.addView(layout);
						}
					}
				}
			} else
			{
				ivAvatarMRecommendations.setVisibility(View.GONE);
			}
		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class MyAdapter extends BaseAdapter
	{

		@Override
		public int getCount()
		{

			return detailLists.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View layout = null;
			ViewHolder viewHolder = null;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				layout = getLayoutInflater().inflate(
				        R.layout.gridviewshareactivity_listview_item, null);
				viewHolder.mImageView = (ImageView) layout
				        .findViewById(R.id.iv_photo_s);
				viewHolder.mTextView = (TextView) layout
				        .findViewById(R.id.tv_text);
				layout.setTag(viewHolder);
			} else
			{
				layout = convertView;
				viewHolder = (ViewHolder) layout.getTag();
			}
			DetailList list = detailLists.get(position);
			UILUtils.displayImageNoAnim(list.getPhotoS(), viewHolder.mImageView);
			viewHolder.mTextView.setText(list.getText());
			return layout;
		}

	}

	class ViewHolder
	{
		private ImageView mImageView;
		private TextView mTextView;
	}

	class ListAdapter extends BaseAdapter
	{

		@Override
		public int getCount()
		{
			// TODO Auto-generated method stub
			return commentsList.size();
		}

		@Override
		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{

			View layout = getLayoutInflater().inflate( R.layout.gridviewshareactivity_listview_footview_listview_item,
			                null);

			ImageView mImageView = (ImageView) layout
			        .findViewById(R.id.iv_avatar_s_item);
			TextView tvName = (TextView) layout
			        .findViewById(R.id.tv_name_user_item);
			TextView tvDate = (TextView) layout
			        .findViewById(R.id.tv_date_added_item);
			TextView tvComment = (TextView) layout
			        .findViewById(R.id.tv_comment_item);
			Comment comment = commentsList.get(position);
			Long dateAdded = comment.getDateAdded();
			Date startDate = new Date(dateAdded * 1000);
			Date endDate = new Date();
			String twoDateDistance = twoDateDistance(startDate, endDate);
			tvDate.setText(twoDateDistance);
			tvName.setText(comment.getUser().getName() + ":");
			tvComment.setText(comment.getComment());
			UILUtils.displayImageNoAnim(comment.getUser().getAvatarS(),
					mImageView);
			return layout;
		}

	}

	@Override
	protected void onStop()
	{
		ImageLoader.getInstance().clearMemoryCache();
		super.onStop();
	}

	private String twoDateDistance(Date startDate, Date endDate)
	{

		if (startDate == null || endDate == null)
		{
			return null;
		}
		long timeLong = endDate.getTime() - startDate.getTime();
		if (timeLong < 60 * 1000)
			return timeLong / 1000 + "秒前";
		else if (timeLong < 60 * 60 * 1000)
		{
			timeLong = timeLong / 1000 / 60;
			return timeLong + "分钟前";
		} else if (timeLong < 60 * 60 * 24 * 1000)
		{
			timeLong = timeLong / 60 / 60 / 1000;
			return timeLong + "小时前";
		} else if (timeLong < 60 * 60 * 24 * 1000 * 7)
		{
			timeLong = timeLong / 1000 / 60 / 60 / 24;
			return timeLong + "天前";
		} else if (timeLong < 60 * 60 * 24 * 1000 * 7 * 4)
		{
			timeLong = timeLong / 1000 / 60 / 60 / 24 / 7;
			return timeLong + "周前";
		} else
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
			return sdf.format(startDate);
		}

	}
}
